"""Utilites s3d module

Usage:
   import s3dutl
"""

import subprocess
import os
import time
import platform
import sys
import smtplib
import shutil
import stat
import socket

def _promptExecuting(cmd):
   print "-----executing(" + cmd + ") in (" + os.getcwd() + ")"

def IsProcessStarted(name):
   #checking if process running
   #***case sensitive***
   if name == "":
      return False
      
   cmd = "C:\\SaberTools\\tools\\python\\psTools_bin\\pslist.exe " + name
   return_code = False
   
   p = subprocess.Popen(cmd, stdout = subprocess.PIPE, stderr = subprocess.PIPE)
   p.wait()
   
   return (p.returncode == 0)

def KillProcess(name):
   #kills process if its running
   #***case sensitive***
   if IsProcessStarted(name):
      cmd = "taskkill /F /T /FI \"IMAGENAME eq " + name + "\""
      #_promptExecuting(cmd)
      p = subprocess.Popen(cmd, stdout = subprocess.PIPE, stderr = subprocess.PIPE)
      p.wait()

def StartProcess(name, cwd_new="."):
   #starts process, and don't waiting for process termination
   if name == "":
      return
   ShellExecute("start " + name, cwd_new)
   
def StartProcessPs(name, cwd_new="."):
   #starts process, and don't waiting for process termination, using PsTools
   if name == "":
      return
   ShellExecute('"C:\\SaberTools\\tools\\python\\psTools_bin\\psexec.exe" -d -w '+cwd_new+' '+name, ".")

def ShellExecute(cmd, cwd_new, log=True):
   #starts process, and waiting for its termination
   if cmd == "":
      return
      
   cwd_cur = os.getcwd()
   os.chdir(cwd_new)
   if log:
      _promptExecuting(cmd)
   os.system(cmd)
   if log:
      print '-----executing done.'
   os.chdir(cwd_cur)

def ProcessExecute(cmd, cwd_new, log=True):
   #starts process, and waiting for its termination
   #returns exit_code
   if cmd == "":
      return 0
      
   cwd_cur = os.getcwd()
   os.chdir(cwd_new)
   if log:
      _promptExecuting(cmd)
   p = subprocess.Popen(cmd)
   subproc_return_code = p.wait()
   if log:
      print '-----executing done.'
   os.chdir(cwd_cur)
   return subproc_return_code

def Sleep(sec):
   time.sleep(sec)

def GetNetName():
   return platform.node()

def DeleteDir(path):
   if os.access(path, os.F_OK):
      print "deleting directory:", path
      ShellExecute("rd /S /Q \"" + path + "\"", ".", False)

def CreateDir(path):
   if not os.access(path, os.F_OK): 
      print "creating directory:", path
      ShellExecute("md \"" + path + "\"", ".", False)

def ClearReadOnly(filename, log = True):
   if os.access(filename, os.F_OK):
      stats = os.stat(filename)
      if len(stats) > 0 and not (stats[stat.ST_MODE] & stat.S_IWRITE):
         if log:
            print "WARNING: removing R\\O flag from file:", filename
         os.chmod(filename, stat.S_IWRITE)

def CopyFile2Dir(file_src, dir_dst):
   if not os.access(file_src, os.F_OK):
      print "source file not found:", file_src
      return
      
   CreateDir(dir_dst)

   filename = file_src[file_src.replace('\\', '/').rfind('/') + 1:]
   file_dst = dir_dst + "\\" + filename
   
   CopyFile2File(file_src, file_dst)

def CopyFile2File(file_src, file_dst, log = True):
   if not os.access(file_src, os.F_OK):
      print "source file not found:", file_src
      return
      
   ClearReadOnly(file_dst, log)
   if log:
      print "copying ("+file_src+") to ("+file_dst+")"
   shutil.copyfile(file_src, file_dst)

def CopyDir2NewDir(dir_src, dir_dst):
   #with all subdirs
   if not os.access(dir_src, os.F_OK):
      print "source dir not found:", dir_src
      return

   print "copying ("+dir_src+") to ("+dir_dst+")"
   shutil.copytree(dir_src, dir_dst)

def CopyFiles2Dir(mask_src, dir_dst):
   if os.access(mask_src[0:mask_src.replace('\\', '/').rfind('/')], os.F_OK):
      CreateDir(dir_dst)
      ShellExecute("copy /Y "+mask_src+" "+dir_dst, ".")

def MoveFiles2Dir(mask_src, dir_dst, log = True):
   if os.access(mask_src[0:mask_src.replace('\\', '/').rfind('/')], os.F_OK):
      CreateDir(dir_dst)
      ShellExecute("move /Y "+mask_src+" "+dir_dst, ".", log)

def DeleteFile(filename, log = True):
   if os.access(filename, os.F_OK):
      if log:
         print "deleting file(s) ", filename, " ..."
      ShellExecute("del /F "  + filename, ".", False)

#filenames must not contain spaces, cause filelist separated by spaces
def DeleteFileList(fileliststr, log = True):
   for item in fileliststr.split(" "):
      DeleteFile(item, log)

def SysExit(code):
   sys.exit(code)

def SendEmail(server_name, fromaddr, toaddrs, subject, message):
   # string, string, array, string, string

   # Add the From: and To: headers at the start!
   body = ("From: %s\r\nTo: %s\r\nSubject:%s\r\n" % (fromaddr, ", ".join(toaddrs), subject)) + message
      
   try:
      server = smtplib.SMTP(server_name)
      server.sendmail(fromaddr, toaddrs, body)
      server.quit()
   except smtplib.SMTPConnectError, msg:
      print "Can't connect to mail server.\r\n", msg
   except socket.error, (code, msg):
      print "Can't connect to mail server.", msg
   except:
      print "Can't send mail, unknown error"


if __name__ == "__main__":
   print __doc__